package com.qf.utils;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qf.user.entity.User;

import java.util.Calendar;
import java.util.Date;

/**
 * 作者：熊剑
 * 时间：2023/10/12
 * 描述：
 */
public class JWTUtil {
    public static String genTokenExpireByHour(Object payload,int hour){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,hour);
        Date expire = instance.getTime();
        //颁发令牌
        String jwtToken = JWT.create()
                //指定payload
                .withClaim("userInfo", JSONUtil.toJsonStr(payload))
                //设置过期时间
                .withExpiresAt(expire)
                .sign(Algorithm.HMAC256("qf"));
        System.out.println(jwtToken);
        //返回jwt令牌
        return jwtToken;
    }

    public static String genTokenExpireByMinute(Object payload,int minute){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,minute);
        Date expire = instance.getTime();
        //颁发令牌
        String jwtToken = JWT.create()
                .withClaim("userInfo", JSONUtil.toJsonStr(payload))
                //设置过期时间
                .withExpiresAt(expire)
                .sign(Algorithm.HMAC256("qf"));
        return jwtToken;
    }

    public static User parseToken(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("qf")).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        return JSONUtil.toBean(verify.getClaim("userInfo").asString(), User.class);
    }
    public static User verifyToken(String token){
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("qf")).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            String userJson = verify.getClaim("user").asString();
            return JSONUtil.toBean(userJson, User.class);
        } catch (Exception e) {
            return null;
        }
    }
}
